package com.zoro.k8sapp.commonutil.network;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;

/**
 * @author zhaoxingwu
 */
public class NetworkUtil {

    /**
     * 获取本机IP
     *
     * @return 本机IP
     * @throws SocketException e
     */
    public static String[] getIp() throws SocketException {
        List<String> addressList = NetworkInterface.networkInterfaces()
                .sorted(Comparator.comparingInt(NetworkInterface::getIndex))
                .map(v -> {
                    StringBuilder name = new StringBuilder(v.getIndex() + "::" + v.getDisplayName() + "::");
                    Enumeration<InetAddress> enumeration = v.getInetAddresses();
                    while (enumeration.hasMoreElements()) {
                        InetAddress address = enumeration.nextElement();
                        name.append(address.getHostName()).append("::")
                                .append("(").append(address.getHostAddress()).append(")-");
                    }

                    return name.toString();
                }).toList();

        return addressList.toArray(new String[0]);
    }
}
